<template>
  <div class="translation-container">
    <el-page-header @back="goBack" title="返回" content="翻译" />
    <div class="translation-content">
      <!-- 左侧部分 -->
      <div class="div-source">
        <div class="source-header">
          <el-form-item label="源语种">
            <el-select v-model="selectedSourceLanguage" placeholder="请选择源语种" id="ddlSourceLang">
              <el-option
                v-for="(name, code) in sourceLanguages"
                :key="code"
                :label="name"
                :value="code"
              />
            </el-select>
          </el-form-item>
          <el-button id="btnTranslate" type="primary" @click="handleTranslate">翻译</el-button>
        </div>
        <div class="source-content">
          <el-input
            id="txtSource"
            v-model="sourceText"
            type="textarea"
            placeholder="请输入需要翻译的文字"
            @input="updateCharCount"
            style="height: 100%"
            ref="sourceInputRef"
          />
        </div>
        <div class="source-footer">
          <el-text type="info">字符数：{{ charCount }}</el-text>
        </div>
      </div>
      
      <!-- 右侧部分 -->
      <div class="div-dist" id="divDist">
        
          <dist-translation 
            v-for="(item, index) in distTranslations" 
            :key="index"
            :show-delete="distTranslations.length > 1"
            :translation-result="item.translationResult"
            :selected-dist-language="item.selectedDistLanguage"
            :translation-preference="item.translationPreference"
            :is-translating="isTranslating"
            @update:selected-dist-language="(val) => item.selectedDistLanguage = val"
            @update:translationPreference="(val) => item.translationPreference = val"
            @delete="removeDistTranslation(index)"
            :class="['dist-translation-item', distItemClass]"
          />
        
      </div>
    </div>
    
    <!-- 悬浮增加按钮 -->
    <div class="floating-add-button">
      <el-button
        id="btnAdd"
        type="primary"
        circle
        @click="addDistTranslation"
        :icon="Plus"
        class="add-button"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, computed, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { SourceLanguages, DistLanguages } from '../config/languages';
import DistTranslation from '../components/DistTranslation.vue';
import { Plus } from '@element-plus/icons-vue';
import { DeepSeekTranslationService } from '../services/translationService';
import { ElLoading, ElMessage } from 'element-plus';

export default defineComponent({
  name: 'TranslationView',
  components: {
    DistTranslation
  },
  setup() {
    const router = useRouter();
    const sourceLanguages = reactive({...SourceLanguages});
    const selectedSourceLanguage = ref('AUTO');
    const detectedLanguage = ref('');
    const sourceText = ref('');
    const sourceInputRef = ref<HTMLInputElement | null>(null); // 添加 ref 用于获取输入框实例
    const charCount = ref(0);
    const isTranslating = ref(false);
    const translationService = new DeepSeekTranslationService();
    
    // 计算属性：根据是否检测到语言来显示自动检测选项的文本
    const autoDetectLabel = computed(() => {
      if (detectedLanguage.value) {
        return `自动检测-${detectedLanguage.value}`;
      }
      return '自动检测';
    });
    
    // 更新源语言显示
    const updateSourceLanguages = () => {
      sourceLanguages.AUTO = autoDetectLabel.value;
    };
    
    // 使用reactive以便能够直接修改对象属性
    const distTranslations = ref([{
      selectedDistLanguage: 'en-US',
      translationResult: '',
      translationPreference: 'standard-neutral-literal-standard'
    }]);
    
    // 计算目标语言模块的宽度类名
    const distItemClass = computed(() => {
      const count = distTranslations.value.length;
      if (count === 1) return 'dist-item-single';
      if (count === 2) return 'dist-item-double';
      if (count === 3) return 'dist-item-triple';
      return 'dist-item-quad';
    });

    const updateCharCount = () => {
      charCount.value = sourceText.value.length;
    };

    const handleTranslate = async () => {
      if (!sourceText.value || !sourceText.value.trim()) {
        ElMessage.error('待翻译的文本为空，请输入需要翻译的内容');
        // 使用 nextTick 确保 DOM 更新后再设置焦点
        nextTick(() => {
          sourceInputRef.value?.focus();
        });
        return;
      }
      
      // 显示全局loading
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '翻译中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      isTranslating.value = true;
      
      // 重置检测到的语言
      if (selectedSourceLanguage.value === 'AUTO') {
        detectedLanguage.value = '';
        sourceLanguages.AUTO = '自动检测';
      }
      
      try {
        // 为每个目标语言组件执行翻译
        let firstDetectedLang = ''; // 用于存储第一个检测到的语言
        
        const translationPromises = distTranslations.value.map(async (item, index) => {
          try {
            let result;
            
            if (selectedSourceLanguage.value === 'AUTO') {
              // 自动检测源语言
              // 将字符串格式的preference转换为Map类型
              const prefMap = convertPreferenceToMap(item.translationPreference);
              
              const response = await translationService.autoDetectTranslate(
                item.selectedDistLanguage, 
                sourceText.value,
                prefMap
              );
              
              // 只处理第一个检测到的语言结果
              if (response.detectedLang && index === 0) {
                // 将语言代码转换为更友好的显示名称
                const langCode = response.detectedLang;
                let langName = '';
                
                // 尝试从现有语言列表中查找对应的语言名称
                Object.entries(SourceLanguages).forEach(([code, name]) => {
                  if (code !== 'AUTO' && langCode.startsWith(code)) {
                    langName = name.toString();
                  }
                });
                
                // 如果没找到对应的语言名称，就使用语言代码
                firstDetectedLang = langName || langCode;
              }
              
              result = response.translation;
            } else {
              // 指定源语言
              // 将字符串格式的preference转换为Map类型
              const prefMap = convertPreferenceToMap(item.translationPreference);
              
              result = await translationService.translate(
                selectedSourceLanguage.value,
                item.selectedDistLanguage,
                sourceText.value,
                prefMap
              );
            }
            
            // 更新翻译结果
            distTranslations.value[index].translationResult = result;
          } catch (error) {
            console.error(`翻译到 ${item.selectedDistLanguage} 失败:`, error);
            distTranslations.value[index].translationResult = `翻译失败: ${error.message || '未知错误'}`;
          }
        });
        
        // 等待所有翻译完成
        await Promise.all(translationPromises);
        
        // 更新检测到的语言显示
        if (selectedSourceLanguage.value === 'AUTO' && firstDetectedLang) {
          detectedLanguage.value = firstDetectedLang;
          updateSourceLanguages();
        }
      } catch (error) {
        console.error('翻译过程中发生错误:', error);
      } finally {
        // 关闭loading
        loadingInstance.close();
        isTranslating.value = false;
      }
    };

    const addDistTranslation = () => {
      distTranslations.value.push({
        selectedDistLanguage: 'en-US',
        translationResult: '',
        translationPreference: 'standard-neutral-literal-standard'
      });
    };

    const removeDistTranslation = (index: number) => {
      distTranslations.value.splice(index, 1);
    };

    // 将字符串格式的preference转换为Map类型
    const convertPreferenceToMap = (prefString: string): Map<string, string> => {
      const prefMap = new Map<string, string>();
      const parts = prefString.split('-');
      
      if (parts.length >= 4) {
        prefMap.set('length', parts[0] || 'standard');
        prefMap.set('tone', parts[1] || 'neutral');
        prefMap.set('style', parts[2] || 'literal');
        prefMap.set('complexity', parts[3] || 'standard');
      }
      
      return prefMap;
    };
    
    const goBack = () => {
      router.go(-1);
    };
    
    return {
      goBack,
      sourceLanguages,
      selectedSourceLanguage,
      sourceText,
      charCount,
      isTranslating,
      distTranslations,
      updateCharCount,
      handleTranslate,
      addDistTranslation,
      removeDistTranslation,
      Plus,
      autoDetectLabel,
      distItemClass,
      sourceInputRef // 导出 ref
    };
  }
});
</script>

<style scoped>
.translation-container {
  padding: 20px;
  width: 98%;
  height: 96%;
  display: flex;
  flex-direction: column;
  background-color: #f9fafc;
}

.translation-content {
  display: flex;
  gap: 24px;
  flex: 1;
  min-height: 400px;
  width: 100%;
}

.div-source {
  flex: 0 0 25%;
  display: flex;
  flex-direction: column;
  border: none;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  transition: all 0.3s ease;
  
}

.div-dist {
  flex: 1;
  display: flex;
  flex-direction: row; /* 改为横向排列 */
  flex-wrap: nowrap; /* 禁止换行 */
  border: none;
  border-radius: 12px;
  overflow: hidden;
  background-color: transparent;
  padding: 0;  
  gap: 20px; /* 添加DistTranslation组件之间的间距 */
}

/* 动态调整目标语言模块的宽度 */
.dist-translation-item {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
  transition: all 0.3s ease;
}

/* 基于类名的动态宽度调整 */
.dist-item-single {
  /* 单个模块占满宽度 */
  width: 100%;
}

.dist-item-double {
  /* 两个模块各占一半 */
  width: 50%;
  flex: 0 0 calc(50% - 10px);
}

.dist-item-triple {
  /* 三个模块各占三分之一 */
  width: 33.33%;
  flex: 0 0 calc(33.33% - 14px);
}

.dist-item-quad {
  /* 四个模块各占四分之一 */
  width: 25%;
  flex: 0 0 calc(25% - 15px);
}

.div-source:hover, .div-dist:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.source-header, .dist-header {
  padding: 16px 20px;
  background-color: #f0f2f5;
  border-bottom: 1px solid #e6e8eb;
  display: flex;
  align-items: center;
  gap: 12px;
}

.source-header :deep(.el-form-item) {
  margin: 0;
  flex: 1;
}

.source-header :deep(.el-select) {
  width: 100%;
}

.source-header :deep(.el-button),
.dist-header :deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.source-content, .dist-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.source-content :deep(.el-textarea),
.source-content :deep(.el-textarea__inner) {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  border-color: #dcdfe6;
  transition: all 0.2s ease;
}

.source-content :deep(.el-textarea__inner):focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.source-content :deep(.el-textarea__inner) {
  flex: 1;
  resize: none;
  font-size: 16px;
  font-family: 'Inter', Arial, sans-serif;
  padding: 12px 16px;
  line-height: 1.6;
}

.source-footer {
  padding: 12px 20px;
  background-color: #f0f2f5;
  border-top: 1px solid #e6e8eb;
  text-align: right;
  font-size: 14px;
  color: #606266;
}

.translation-result {
  height: 100%;
  font-size: 16px;
  color: #303133;
  line-height: 1.6;
}

/* 悬浮增加按钮样式 */
.floating-add-button {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 1000;
}

.add-button {
  width: 56px;
  height: 56px;
  font-size: 22px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.add-button:hover {
  transform: translateY(-5px) scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}


/* 响应式调整 */
@media (max-width: 768px) {
  .translation-content {
    flex-direction: column;
  }
  
  .div-source {
    margin-bottom: 20px;
  }
  
  .floating-add-button {
    right: 20px;
    bottom: 20px;
  }
}
</style>